package com.yxs.school.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yxs.school.api.entity.Article;
import com.yxs.school.api.entity.ArticleVo;
import com.yxs.school.api.service.impl.ArticleServiceImpl;
import com.yxs.school.result.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文章 前端控制器
 * </p>
 *
 * @author whp
 * @since 2019-11-15
 */
@RestController
@RequestMapping("/api/article")
public class ArticleController {
    @Resource
    ArticleServiceImpl articleService;

    @PostMapping("save")
    public R add(@RequestBody Article article) {
        System.out.println(article);
        boolean data=articleService.save(article);
        if(data)
       return R.data(200,null,"添加成功") ;
        else   return R.data(400,null,"添加失败") ;

    }
    @DeleteMapping("delete")
    public R remove(@RequestBody List<Integer> ids){
        System.out.println(ids);
        boolean flag=articleService.removeByIds(ids);
        if(flag){
          return   R.data(200,"成功删除"+ids.size()+"条","成功");
        }else {
            return   R.data(400,null,"失败");
        }
    }
    @PatchMapping("update")
    @PutMapping("update")
    public R update(@RequestBody Article article){
        boolean flag=articleService.updateById(article);
        if(flag){
         return  R.data(200,null,"更新成功");
        }else {
            return  R.data(400,null,"更新失败");
        }
    }
    @GetMapping("list")
    public R list(Integer page,Integer size,String keyword,String order){
        PageHelper.startPage(page,size);
        QueryWrapper<Article> wrapper =new QueryWrapper<>();
//        if (keyword!=null||!"".equals(keyword)){
//            wrapper.like("title",keyword);
//            wrapper.or();
//            wrapper.like("intro",keyword);
//        }
        if (order!=null||!"".equals(order)){
            wrapper.orderByAsc("create_time");
        }
        PageInfo<ArticleVo> pageInfo =new PageInfo<>(articleService.selectListByType(wrapper));
        int sum = (int)pageInfo.getTotal();
        List<ArticleVo> list= pageInfo.getList();
        Map<String,Object> res=new HashMap<>(16);
        res.put("total",sum);
        res.put("list",list);
        return R.data(200,res,"成功");
    }
    @GetMapping("detail")
    public R detail(Integer id) {
        Article article= articleService.getById(id);
        return R.data(200,article,"");
    }

}
